#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 3e5 + 5;
int n, m;
int a[N];

int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cin >> n;
  rep(i, 1, n) cin >> a[i];
  ll ans = 0, sum = 0;
  stack<int> mx;
  rep(i, 1, n) {
    while (mx.size() && a[mx.top()] <= a[i]) {
      int r = mx.top();
      mx.pop();
      int l = mx.size() ? mx.top() : 0;
      sum -= 1ll * a[r] * (r - l);
    }
    int r = i, l = mx.size() ? mx.top() : 0;
    sum += 1ll * a[r] * (r - l);
    ans += sum;
    mx.push(i);
  }
  sum = 0;
  stack<int> mn;
  rep(i, 1, n) {
    while (mn.size() && a[mn.top()] >= a[i]) {
      int r = mn.top();
      mn.pop();
      int l = mn.size() ? mn.top() : 0;
      sum -= 1ll * a[r] * (r - l);
    }
    int r = i, l = mn.size() ? mn.top() : 0;
    sum += 1ll * a[r] * (r - l);
    ans -= sum;
    mn.push(i);
  }
  cout << ans;
  return 0;
}